<template>
    <!-- 供应商奖惩-新增 -->
    <div class="e-form">
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    ref="formData"
                    :rules="rules"
                    label-width="150px"
                >
                <BillTop title="供应商奖惩新增" @cancel="handleClose"></BillTop>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="供应商名称" prop="outerName">
                                <el-input
                                    v-model="formData.outerName"
                                    placeholder="请填写"
                                    maxlength="100"
                                    @change="outerNameChange"
                                >
                                    <i
                                        slot="suffix"
                                        class="el-icon-document-copy"
                                        @click="onFbUnit"
                                    ></i>
                                </el-input>
                                <el-button
                                v-if="isDisable"
                                    style="
                                        background-color: rgb(22, 155, 213);
                                        color: #fff;
                                        margin-left: 20px;
                                    "
                                    @click="onSelect1"
                                    >查看</el-button
                                >
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="统一社会信用代码"
                                prop="creditCode"
                            >
                                <el-input
                                    :disabled="isDisable"
                                    v-model="formData.creditCode"
                                    placeholder="请填写"
                                    maxlength="18"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item v-if="!isDisable" label="合同名称:">
                                <span> {{ '- -' }}</span>
                            </el-form-item>
                            <el-form-item v-else label="合同名称">
                                <el-input
                                    v-model="formData.contractName"
                                    readonly
                                    placeholder="请选择"
                                >
                                    <i
                                        slot="suffix"
                                        class="el-icon-document-copy"
                                        @click="onContract"
                                    ></i>
                                </el-input>
                                <el-button
                                    style="
                                        background-color: rgb(22, 155, 213);
                                        color: #fff;
                                        margin-left: 20px;
                                    "
                                     @click="onSelect2"
                                    >查看</el-button
                                >
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="奖惩类型"
                                prop="rewardsOrPunishmentName"
                            >
                                <el-radio-group
                                    v-model="formData.rewardsOrPunishmentName"
                                    @change="onRAPType"
                                >
                                    <el-radio
                                        v-for="item in rewardsOrPunishmentList"
                                        :key="item.kvId"
                                        :label="item.kvKey"
                                        :value="item.kvValue"
                                    ></el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="13">
                            <el-form-item
                                label="供应商类型"
                                prop="outerTypeKey"
                            >
                                <el-checkbox
                                    :disabled="isDisable"
                                    :indeterminate="isIndeterminate"
                                    v-model="checkAll"
                                    @change="handleCheckAllChange"
                                    style="margin-right: 20px"
                                    >全选</el-checkbox
                                >
                                <el-checkbox-group
                                    :disabled="isDisable"
                                    v-model="formData.outerTypeKey"
                                    @change="handleCheckedCitiesChange"
                                >
                                    <el-checkbox
                                        v-for="item in typeList"
                                        :key="item.kvId"
                                        :label="item.kvKey"
                                        :value="item.kvId"
                                        style="margin-top: 5px"
                                    ></el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-col>
                        <el-col v-show="DateShow" :span="11">
                            <el-form-item label="开始日期：">
                                <el-date-picker
                                    v-model="formData.startDate"
                                    @change="DateChange"
                                    type="date"
                                    placeholder="选择日期"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="奖惩原因" prop="opinion">
                            <el-input
                                type="textarea"
                                v-model="formData.opinion"
                                placeholder="请输入内容"
                                :rows="2"
                                maxlength="500"
                                 show-word-limit
                            ></el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="机构"
                                >{{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                {{ statusLable(formData.state) }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                >保存</el-button
            >
            <el-button @click="cancel()">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import { showSuccessPop, openAppClient, selectDataClient } from '@/utils/common'
import subcontractorRAP from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorRAP.js'
import supplier from '@/api/OutsourcingartyAdmin/supplier/supplier.js'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import { creditCodeVerification } from '@/utils/rules'
export default {
    data () {
        return {
            //表单数据
            formData: {
                outerName: '', //分包商名称
                creditCode: '', //统一社会信用代码
                contractName: '', //合同名称
                rewardsOrPunishment: '', //奖惩类型id
                rewardsOrPunishmentName: '', //奖惩类型名称
                startDate: '', //开始日期
                endDate: '', //结束日期
                opinion: '', //评价意见
                score: '', //奖惩等级或得分
                state: '', //状态
                outerId: '', //外包方id
                orgName: '', //机构
                id: '', //处罚ID
                manageOrgId: '', //管理单位ID
                manageOrgName: '', //管理单位
                orgId: '', //机构ID
                outerTypeKey: [], //	外包方类型名称
                outerTypeValue: [], //外包方类型ID
                remark: '', //备注
                type: '1', //供应商
                isOuterUnit: true, //是否是库外单位[true:库外，false:库内]
            },

            //类型列表
            typeList: [],
            checkAll: false, //是否全选
            //奖惩类型列表
            rewardsOrPunishmentList: [],
            isIndeterminate: true,
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            newBase: {}, //分包商基础数据
            DateShow: false, //开始时间和结束时间是否展示
            isDisable: false, //库内单位禁用统一社会信用代码
            contractId: '', //合同id
            type: '', //合同类型
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: creditCodeVerification,
                        trigger: 'blur'
                    }
                ],
                //供应商名称
                outerName: [
                    {
                        required: true,
                        message: '请选择供应商名称',
                        trigger: 'blur'
                    }
                ],
                //分包商类型
                outerTypeKey: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                //奖惩类型
                rewardsOrPunishmentName: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                //开始时间
                startDate: [
                    {
                        required: true,
                        message: '请选择开始时间',
                        trigger: 'change'
                    }
                ],
                //奖惩原因
                opinion: [
                    {
                        required: true,
                        message: '请输入奖惩原因',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        }
    },
    components: {},
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.formData.orgId = data.userInfo.orgInfo.orgId //初始化机构id
        this.formData.orgName = data.userInfo.orgInfo.orgName //初始化机构名字
        this.getTypeData() //进入页面获取类型选择框数据
    },
    mounted () {},
    beforeDestroy () {},
    methods: {
        ...mapMutations(['setPopConfirm']),
        //获取类型选择框数据
        getTypeData () {
            call.getCredentialTree({ name: '外包方类型', id: '0' }).then(
                res => {
                    let id = ''
                    // 获取想要的类型id
                    res.map(item => {
                        if (item.kvKey == '供应商') {
                            id = item.kvId
                        }
                    })
                    call.getCredentialTree({ name: '外包方类型', id: id }).then(
                        res => {
                            this.typeList = res
                        }
                    )
                }
            )
            call.getCredential('信用评价类型').then(res => {
                let data = res.filter(item => {
                    return item.kvKey == '奖励' || item.kvKey == '惩罚'
                })
                this.rewardsOrPunishmentList = data
            })
        },
        //保存按钮
        async save () {
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    let data = JSON.parse(JSON.stringify(this.formData))
                    data.outerTypeKey = data.outerTypeKey.join(',')
                    data.outerTypeValue = data.outerTypeValue.join(',')
                    let datas = await subcontractorRAP.AddSubcontractorRAP(
                        data
                    )
                    if (datas.code != 200) {
                        this.clientPop(
                            'info',
                            '保存成功！是否进行下一步操作？',
                            this.gocallback(datas),
                            null,
                            this.cancelCallBack(datas)
                        )
                    } else {
                        showSuccessPop('保存失败')
                    }
                } else {
                    this.clientPop('err', '必填项未填')
                    return false
                }
            })
        },
        // 保存成功继续回调
        gocallback (billid) {
            return () => {
                this.$router.push({
                    path: '/supplierPunishmentEdit',
                    query: { billid }
                })
            }
        },
        // 保存成功，取消回调
        cancelCallBack (billid) {
            return () => {
                this.$router.push({
                    path: '/supplierPunishment',
                    query: { billid }
                })
            }
        },
        //取消按钮
        cancel () {
            this.$router.push('/supplierPunishment')
        },
        // 外包方类型全选
        handleCheckAllChange (val) {
            this.formData.outerTypeValue = []
            this.formData.outerTypeKey = val
                ? this.typeList.map(item => {
                    return item.kvKey
                })
                : []
            this.isIndeterminate = false
            // 循环拿到id
            this.typeList.map(item => {
                this.formData.outerTypeValue.push(item.kvValue)
            })
        },
        //外包方类型选择
        handleCheckedCitiesChange (value) {
            this.formData.outerTypeValue = []
            let checkedCount = value.length
            this.checkAll = checkedCount === this.typeList.length
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.typeList.length
            // 循环拿到id
            this.typeList.map(item => {
                value.map(Valitem => {
                    if (item.kvKey == Valitem) {
                        this.formData.outerTypeValue.push(item.kvValue)
                    }
                })
            })
        },
        // 供应商弹窗选择详情
        onFbUnit () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    businessUnitTypes: [], //外来单位类型
                    keyword: '', //模糊查询关键字
                    limit: 10, //每页显示条数
                    orgId: '', //单据机构
                    outerTypes: [], //	外包方类型
                    page: 1, //当前页数
                    states: [], //单据状态
                    type: [1] //类型（0分包商 1供应商 2 往来单位 3 事实外包方）
                }),
                Title: '分包商选择'
            }).then(val => {
                // 选择库内单位，统一社会信用代码禁用
                this.isDisable = true
                this.formData.outerName = val[0].outerName
                this.formData.outerId = val[0].outerId
                this.formData.creditCode = val[0].creditCode
                this.formData.outerTypeKey = val[0].outerType.split(',')
                this.formData.outerTypeValue = val[0].outerTypeValue.split(',')
                // 查回来了就是库内单位
                this.formData.isOuterUnit = false//是否是库外单位
                // 禁用与启用奖惩类型
                this.rewardsOrPunishmentList.map(item=>{
                    if(item.kvValue == '2') {
                        item.disabled = false
                        this.formData.rewardsOrPunishment = ''
                        this.formData.rewardsOrPunishmentName = ''
                    }
                })
            })
        },
        // 供应商名称验证
        async outerNameChange (val) {
            if (val) {
                let data = await supplier.getsupplierName({
                    supplierName: val
                })
                if (data.id) {
                    this.formData.creditCode = data.creditCode
                    this.formData.outerId = data.supplierId
                    this.formData.outerTypeKey =
                        data.supplierTypeKey.split(',')
                    this.formData.outerTypeValue =
                        data.supplierTypeValue.split(',')
                    this.isDisable = true
                    // 禁用与启用奖惩类型
                    this.rewardsOrPunishmentList.map(item=>{
                        if(item.kvValue == '2') {
                            item.disabled = false
                            this.formData.rewardsOrPunishment = ''
                            this.formData.rewardsOrPunishmentName = ''
                        }
                    })
                    // 查回来了就是库内单位
                    this.formData.isOuterUnit = false//是否是库外单位
                } else {
                    this.formData.creditCode = ''
                    this.formData.outerTypeKey = []
                    this.formData.outerTypeValue = []
                    this.formData.score = ''
                    this.formData.outerId = ''
                    this.isDisable = false
                    this.formData.isOuterUnit = true//是否是库外单位
                    // 禁用与启用奖惩类型
                    this.rewardsOrPunishmentList.map(item=>{
                        if(item.kvValue == '2') {
                            item.disabled = true
                            this.formData.rewardsOrPunishment = '1'
                            this.formData.rewardsOrPunishmentName = '惩罚'
                        }
                    })
                }
            }
        },
        ...mapMutations(['setSelectedInfo']),
        // 合同名称查询
        onContract () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken:
                    '/subcontract/thirdParty/getSupplierContractInfosByOrgId', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    types: [2] //合同类型集合，1：分包合同，2：机材支出合同
                }), //参数
                Title: '分包商合同选择'
            }).then(val => {
                this.formData.contractName = val[0].contractName //合同名称
                this.contractId = val[0].contractId//合同id
                this.type = val[0].type//合同类型
            })
        },
        //奖惩类型
        async onRAPType (val) {
            this.rewardsOrPunishmentList.map(item => {
                if (item.kvKey == val) {
                    this.formData.rewardsOrPunishment = item.kvValue
                }
            })
            if (val == '惩罚') {
                this.DateShow = true
            } else {
                this.DateShow = false
            }
        },

        // 开始日期选择
        DateChange (val) {
            var year = val.getFullYear() //年
            var month = val.getMonth() + 1 //月
            var date = val.getDate() //日
            var str = year + '-' + month + '-' + date
            this.formData.startDate = str
        },
        // 供应商名称页面
        onSelect1 () {
            openAppClient(`/supplierbePutinstorageExamine?isview=true&creditCode=${this.formData.creditCode}`, '供应商详情', function () {
            })
        },
        // 供应商合同页面
        onSelect2 () {
            // 类型: 1、物资采购 2、周材租赁 3、加工合同 4、设备采购合同 5、设备租赁合同 6、服务采购合同
            if(this.type == 1) {
                openAppClient(`/ctMaterialApplyShow?isview=true&billid=${this.contractId}`, '物资采购合同详情', function () {
                })
            }else if(this.type == 2) {
                openAppClient(`/ctRevolvMaterialApplyShow?isview=true&billid=${this.contractId}`, '周材租赁合同详情', function () {
                })
            }else if(this.type == 3) {
                openAppClient(`/processingContractApplyShow?isview=true&billid=${this.contractId}`, '加工合同详情', function () {
                })
            }else if(this.type == 4) {
                openAppClient(`/ctEquipmentPurchaseApplyShow?isview=true&billid=${this.contractId}`, '设备采购合同详情', function () {
                })
            }else if(this.type == 5) {
                openAppClient(`/ctEquipmentLeaseApplyShow?isview=true&billid=${this.contractId}`, '设备租赁合同详情', function () {
                })
            }else if(this.type == 6) {
                openAppClient(`/serviceProcurementApplyShow?isview=true&billid=${this.contractId}`, '服务采购合同详情', function () {
                })
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
